package indi.zhang.rocketmq.utils;

import com.yomahub.tlog.core.mq.TLogMqWrapBean;
import indi.zhang.common.base.Result;
import indi.zhang.mq.MessageContent;
import indi.zhang.mq.api.Producer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import cn.hutool.core.util.IdUtil;

@Slf4j
@RequiredArgsConstructor
public class RktMqProducer implements Producer {

    private final RocketMQTemplate rocketMQTemplate;

    /**
     * 通用message发送接口，tLog版本
     * @param messageContent
     * @return
     */
    @Override
    public Result<Object> sendEventMessageTLog(MessageContent messageContent) {
        try {
            String key = IdUtil.fastUUID();
            log.info("消息key={}",key);
            TLogMqWrapBean<MessageContent> tLogMqWrap = new TLogMqWrapBean<>(messageContent);
            Message<TLogMqWrapBean<MessageContent>> message = MessageBuilder.withPayload(tLogMqWrap).setHeader("KEYS",key).build();
            rocketMQTemplate.send(messageContent.getTopic()+":"+messageContent.getMessageType(), message);
            log.info("消息发送成功 topic[{}],key[{}],data[{}]",messageContent.getTopic(),key,message.getPayload());
        } catch (Exception e) {
            log.error("消息发送失败 topic[{}]],data[{}]",messageContent.getTopic(),messageContent);
            return Result.error();
        }
        return Result.success();
    }

    /**
     * 通用message发送接口
     * @param messageContent
     * @return
     */
    @Override
    public Result<Object> sendEventMessage(MessageContent messageContent) {
        try {
            String key = IdUtil.fastUUID();
            log.info("消息key={}",key);
            Message<MessageContent> message = MessageBuilder.withPayload(messageContent).setHeader("KEYS",key).build();
            rocketMQTemplate.send(messageContent.getTopic()+":"+messageContent.getMessageType(), message);
            log.info("消息发送成功 topic[{}],key[{}],data[{}]",messageContent.getTopic(),key,message.getPayload());
        } catch (Exception e) {
            log.error("消息发送失败 topic[{}]],data[{}]",messageContent.getTopic(),messageContent);
            return Result.error();
        }
        return Result.success();
    }
}
